// Handle combogrid
App.directive('edCombogrid', ['$parse', 'Page', function ($parse, Page) {

    return {

        restrict: 'A',

        // restrict and template attributes are the same as before.
        // we don't need anymore to bind the value to the external ngModel
        // as we require its controller and thus can access it directly
        scope: {
            model: '@ngModel'
        },
        // the 'require' property says we need a ngModel attribute in the declaration.
        // this require makes a 4th argument available in the link function below
        require: '?ngModel',

        template: function (elem, attrs) {
            var id = Metronic.getUniqueID(), gridId = attrs.edCombogrid || ('grid_' + id);
            var option = AppUtil.jsonfy(attrs.options), comboOptions = [];
            // 传递给ed-combo的配置
            if (angular.isDefined(option.disabled)) {
                comboOptions.push('disabled:' + option.disabled);
            }
            comboOptions.push("placeholder:'" + (attrs.placeholder || '') + "'");
            if (option.panelWidth) {
                comboOptions.push('panelWidth:' + option.panelWidth);
            }
            // 查询条件
            var queryHtml = $(elem).html();
            if (queryHtml && queryHtml.length > 0) {
                $(elem).empty();
                queryHtml = $(queryHtml).append('<button type="button" class="btn btn-sm green" ng-click="query()"><i class="fa fa-search"></i> 查询</button>').prop('outerHTML');
            }

            return '<div ed-combo="combo_' + id + '" data-options="' + comboOptions.join(',') + '">'
                    + (queryHtml || '')
                    + '<div style="width: 100%" ed-grid-dynamic="' + gridId + '" ed-url="' + option.url + '"></div></div>';
        },

        link: function (scope, elem, attrs, ngModelController) {

            var gridEle = $(elem).find('[ed-grid-dynamic]');
            var grid = scope[gridEle.attr('ed-grid-dynamic')];
            var combo = scope[gridEle.parents('[ed-combo]').attr('id')];

            grid.options = {
                scroller: true,
                paging: true// 是否翻页
            };
            grid.column_defs = [
                {
                    target: 0,
                    template: function(row){
                        return '<a href="javascript:void(0)" ed-click="select"><i class="fa fa-circle-thin"></i></a>';
                    }
                }
            ];
            grid.select = function(row) {
                scope.setValue(row);
                combo.hide();
            }

            var option = AppUtil.jsonfy(attrs.options);
            // 设置动态表格
            option.columns[0].unshift({col:'_index',name:'选择',width:60});
            grid.setDynamicTable(option.columns, option.data);
            gridEle.find('table').css('width', '98%').css('margin', '1%');

            // 设置值
            scope.setValue = function(row) {
                var modelName = AppUtil.getModelName(attrs.ngModel);
                // 如果model的名称和id相同，则值绑定id，否则绑定item
                if (modelName == option.idField) {
                    ngModelController.$setViewValue(row[option.idField]);
                } else {
                    ngModelController.$setViewValue(row);
                }
                ngModelController.$render(row[option.textField]);
            };

            // 查询
            scope.query = function() {
                var params = [];
                $(gridEle).prev('.param').find('[ng-model]').each(function(i, model) {
                    var modelName = $(model).attr('ng-model');
                    params[AppUtil.getModelName(modelName)] = AppUtil.getModelValue(scope, modelName);
                });
                grid.query(params);
            }
            // when model change, update our view (just update the div content)
            ngModelController.$render = function(text) {
                //scope.$broadcast("combo.close", text);
                if (typeof ngModelController.$viewValue !== 'undefined' && !$.isEmptyObject(ngModelController.$viewValue)) {
                    if (typeof text !== 'undefined') {
                        combo.setText(text).hide();
                    } else {
                        var params = option.data || {};
                        params[option.idField] = ngModelController.$viewValue;

                        Page.ajaxGet(option.url, params, function(resp) {
                            var rows = resp.data.rows;
                            if (rows.length > 0) {
                                $(rows).each(function(i, row) {
                                    if (row[option.idField] == ngModelController.$viewValue) {
                                        combo.setText(row[option.textField]);
                                        return false;
                                    }
                                });
                            }
                        }, function() {
                            combo.setText(ngModelController.$viewValue);
                        });
                    }
                } else {
                    combo.setText('');
                }
            };
        }

    };
}]);